import time

from base_restful.http_utils import *
from my_data.local_data import LocalData
from .const import BaseInfo

data = LocalData()


def create_order():
    """
    创建订单，订单数据模板在my_data下order.json
    :return:
    """
    return http_post_json('/order/orderPrimeval/addOrder', data.get_create_order_need_data())


def create_order_pc_activtiy():
    """
    修理厂创建活动订单，订单数据模板在my_data下order.json
    :return:
    """
    activity_data = data.get_create_order_activity_data(BaseInfo.active)
    print('创建订单：', activity_data)
    return http_post_json('order/orderPrimeval/addOrderPc', activity_data)


# 选择支付方式为先货后款
def choose_pay_way_xhhk(order_id):
    """
    更改订单的支付方式为货到付款
    :param order_id:
    :return:
    """
    param = {"orderId": order_id, "payWay": 4}
    return http_post_json('/order/orderMain/choosePayWay', param)


# 选择支付方式为先货后款
def choose_pay_way_zq(order_id):
    """
    更改订单的支付方式为货到付款
    :param order_id:
    :return:
    """
    param = {"orderId": order_id, "payWay": 3}
    return http_post_json('/order/orderMain/choosePayWay', param)


def get_before_return_goods(order_id):
    """
    查询订单可以退货的商品
    :param order_id:
    :return:
    """
    param = {"orderId": order_id}
    return http_post_json('/order/orderMain/getBeforeReturnGoods', param)


# 售前取消
def update_order(order_id):
    """
    售前取消，每种商品取消一个
    :param order_id:
    :return:
    """
    reGoods = get_before_return_goods(order_id)
    param = {"orderId": order_id, "cancelReason": "python test cancel"}
    p_list = []
    listData = list(reGoods['listData'])
    for data in listData:
        p_list.append({"orderDetailId": data['orderDetailId'], "returnQuantity": "1"})
    param['orderMainDetailList'] = p_list
    print('开始执行售前取消，数据为：')
    print(param)
    return http_post_json('/order/orderMain/updateOrder', param)


# 售前取消
def update_order_cancel_all(order_id):
    """
    售前取消，每种商品取消一个
    :param order_id:
    :return:
    """
    reGoods = get_before_return_goods(order_id)
    param = {"orderId": order_id, "cancelReason": "python test cancel"}
    p_list = []
    listData = list(reGoods['listData'])
    for data in listData:
        p_list.append({"orderDetailId": data['orderDetailId'], "returnQuantity": data['quantity']})
    param['orderMainDetailList'] = p_list
    print('开始执行售前取消，数据为：')
    print(param)
    return http_post_json('/order/orderMain/updateOrder', param)


def get_order_details(order_id):
    """
    查询订单详情
    :param order_id:
    :return:
    """
    param = {"orderId": order_id}
    return http_post_json('/order/orderMain/getDetail', param)


def get_after_return_goods(order_id):
    """
    获取可退货商品列表
    :param order_id:
    :return: {"result":true,"message":"成功","code":0,"listData":[]}
    """
    param = {"orderId": order_id}
    return http_post_json('/order/orderMain/getAfterReturnGoods', param)


def order_return_insert_all(order_id):
    """
    可退货商品，全部退货
    :param order_id:
    :return:
    """
    ulist = list(get_after_return_goods(order_id)['listData'])
    param = {"returnReason": "自动退货脚本，执行退货申请", "applySource": 2, "orderId": order_id}
    details = []
    for d in ulist:
        details.append({"applyQuantity": d['quantity'], "orderDetailId": d['orderDetailId'], "goodsId": d['goodsId']})
    param['details'] = details
    print('开始执行全部退货，退货数据为：')
    print(param)
    return http_post_json('/order/orderReturn/insert', param)


def order_return_insert_part(order_id):
    """
    可退货商品，部分退货（随机）
    :param order_id:
    :return:
    """
    ulist = list(get_after_return_goods(order_id)['listData'])
    param = {"returnReason": "自动退货脚本，执行退货申请", "applySource": 2, "orderId": order_id}
    details = []
    for d in ulist:
        if len(details) % 2 == 0:
            quantity = d['quantity'] - 1
            if quantity == 0:
                quantity = 1
            details.append(
                {"applyQuantity": quantity, "orderDetailId": d['orderDetailId'], "goodsId": d['goodsId']})
    param['details'] = details
    print('开始执行部分退货，退货数据为：')
    print(param)
    return http_post_json('/order/orderReturn/insert', param)


def get_wait_return_list_by_order_id(order_id):
    """
    根据订单号获取待处理的退货单
    :param order_id:
    :return:{"result":true,"message":"查询成功。","code":0,"listData":[],"page":1,"pageSize":10,"totalPage":1,"total":5}
    """
    param = {"status": 1, "RefundTime": [], "ReturnTime": [], "orderId": order_id, "pageSize": 999999, "page": 1}
    return http_post_json('/order/orderReturn/selectAllByParam', param)


def get_wait_hand_return_detail_return_id(return_id):
    """
    根据退货单号，获取待处理退货单详情
    :param return_id:退回单号
    :return:
    """
    param = {"returnOrderId": return_id}
    return http_post_json('/order/orderReturn/waitReturnDetail', param)


def get_return_detail_return_id(return_id):
    """
    根据退货单号，获取退货单详情
    :param return_id:退回单号
    :return:
    """
    param = {"returnOrderId": return_id}
    return http_post_json('/order/orderReturn/selectDetail', param)['data']


def hand_all_return_pass(order_id):
    """
    处理所有待审退货单为通过状态
    :param order_id:
    :return:
    """
    all_result = []
    r_list = list(get_wait_return_list_by_order_id(order_id)['listData'])
    for r in r_list:
        r_detail = get_wait_hand_return_detail_return_id(r['returnOrderId'])['data']
        param = {"apartList": [],
                 "returnOrderId": r['returnOrderId'],
                 "auditId": r_detail['auditId'],
                 "orderId": order_id,
                 "remarkList": [{"auditPerson": "lijiashu", "remark": "自动审核通过"}]}
        apart_list = []
        for goods in r_detail['details']:
            apart_list.append(
                {"name": goods['name'],
                 "applyQuantity": goods['applyQuantity'],
                 "returnDetailId": goods['applyQuantity'],
                 "returnType": 1,
                 "orderDetailId": goods['orderDetailId'],
                 "salesPrice": goods['salesPrice'],
                 "giftStatus": goods['giftStatus'],
                 "returnPrice": goods['returnPrice']})
        param['apartList'] = apart_list
        r_result = http_post_json('/order/orderReturn/saveReturnInfo', param)
        all_result.append({'param': param, 'result': r_result})
        # 重复提交
        time.sleep(3)
    return all_result


def get_return_wait_stock_in_list_by_order_id(order_id):
    """
    获取待入库的退货单列表
    :param order_id:
    :return:{"result":true,"message":"查询成功。","code":0,"listData":[],"page":1,"pageSize":10,"totalPage":1,"total":5}
    """
    param = {"status": 3, "RefundTime": [], "ReturnTime": [], "orderId": order_id, "pageSize": 999999, "page": 1}
    r_list = list(http_post_json('/order/orderReturn/selectAllByParam', param)['listData'])
    param['status'] = 2
    r_list1 = http_post_json('/order/orderReturn/selectAllByParam', param)['listData']
    for item in r_list1:
        r_list.append(item)
    return r_list


def order_sales_confirm_receipt(order_id):
    """
    销售助手收款
    :param order_id:
    """
    print("销售助手收款")
    print("orderId", order_id)
    param = {"orderIds": [order_id]}
    print(param)
    r_list = http_post_json('/order/salesAssistant/confirmReceipt', param)
    return r_list
